<script setup lang="ts">
import {ref, reactive, nextTick} from "vue";
import type {Dishes, DishesSearchParam} from "@/api/dishes/type";
import {addDishes, deleteDishes, getDishesList, updateDishes} from "@/api/dishes";
import type {Page} from "@/api/page/types";
import EtoakPager from "@/views/compoment/EtoakPager.vue";
import {ElMessage, ElMessageBox, type FormRules, type UploadProps, type UploadUserFile} from "element-plus";
import type {Ingredients} from "@/api/ingredients/types";
import {getIngredientsByType} from "@/api/ingredients";
import {useTokenStore} from "@/stores/tokenStore";

const tokenStore = useTokenStore()

const base_url = import.meta.env.VITE_APP_BASE_API

/* 查询功能 */
const total = ref(0)
const dishesList = ref<Dishes[]>([])

const queryForm = reactive<DishesSearchParam>({
  pageNum: 1,
  pageSize: 5,
  name: ''
})
const queryFormRef = ref()

const listDishes = () => {
  getDishesList(queryForm).then((page: Page<Dishes>) => {
    total.value = page.total
    dishesList.value = page.rows
  }).catch(e => {
    console.log(e)
  })
}
/* 点击查询表单的搜索按钮 */
const search = () => {
  queryForm.pageNum = 1
  listDishes()
}
/* 重置查询表单 */
const resetQueryForm = () => {
  queryFormRef.value.resetFields()
  search()
}

/* 添加 */
const title = ref('添加菜品')
const dishesFormVisible = ref(false)
const dishesFormRef = ref()
const dishesForm = ref<Dishes>({
  name: '',
  url: '',
  main: '',
  mainNum: 10,
  minor: '',
  minorNum: 10,
  seasoning: '',
  seasoningNum: 10,
  description: ''
})

const dishesFormRules = ref<FormRules>({
  name: [{required: true, message: '请输入菜品名称'}],
  url: [{required: true, message: '请上传菜品封面'}],
  main: [{required: true, message: '请选择主要食材'}],
  mainNum: [{required: true, message: '请填写主要食材份量'}],
  minor: [{required: true, message: '请选择辅助食材'}],
  minorNum: [{required: true, message: '请填写辅助食材份量'}],
  seasoning: [{required: true, message: '请选择配料'}],
  seasoningNum: [{required: true, message: '请填写配料份量'}],
  description: [{required: true, message: '请输入菜品描述'}]
})

const fileList = ref<UploadUserFile[]>([])
const fileLimit = ref(1)

const handleSuccess: UploadProps['onSuccess'] = (resp, file, files) => {
  dishesForm.value.url = resp.data
  dishesFormRef.value.validateField('url')
}

/* 上传前执行 */
const handleBeforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isJPG = file.type == 'image/jpeg'
  const isPNG = file.type == 'image/png'
  const isLt1MB = file.size / 1024 / 1024 < 1
  if (!isJPG && !isPNG) {
    ElMessage.warning('仅支持jpg/png格式')
    return false
  }

  if (!isLt1MB) {
    ElMessage.warning('图片大小不能超过1MB')
    return false
  }

}

/* 当超出上传文件个数限制时执行 */
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(`只能上传 ${fileLimit} 张图片`)
}

/* 删除图片时执行 */
const handleRemove: UploadProps['onRemove'] = (file) => {
  dishesForm.value.url = ''
  fileList.value = []
  dishesFormRef.value.validateField('url')
}
const handleAdd = () => {
  dishesFormVisible.value = true
  title.value = '添加菜品'
  nextTick(() => {
    dishesForm.value = {
      name: '',
      url: '',
      main: '',
      mainNum: 10,
      minor: '',
      minorNum: 10,
      seasoning: '',
      seasoningNum: 10,
      description: ''
    }
    fileList.value = []
    dishesFormRef.value.resetFields()
  })
}

const mainList = ref<Ingredients[]>([])
const minorList = ref<Ingredients[]>([])
const seasoningList = ref<Ingredients[]>([])

const getIngredientsList = async () => {
  try {
    mainList.value = await getIngredientsByType('1')
    minorList.value = await getIngredientsByType('2')
    seasoningList.value = await getIngredientsByType('3')
  } catch (e) {
    console.log(e)
  }
}
/* 更新 */
const handleEdit = (row: Dishes) => {
  dishesFormVisible.value = true
  title.value = '编辑菜品信息'
  dishesForm.value = {...row}
  fileList.value = [{name: row.url, url: base_url + row.url}]
}

/* 删除 */
const handleDelete = (id: number) => {
  ElMessageBox.confirm('确认删除?', '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      await deleteDishes(id)
      setTimeout(() => {
        listDishes()
      }, 500)
    } catch (e) {
      console.log(e)
    }
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}

/* 点击确认 */
const confirm = () => {
  dishesFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (!dishesForm.value.id) {
        await addDishes(dishesForm.value)
      } else {
        await updateDishes(dishesForm.value)
      }
      dishesFormVisible.value = false
      setTimeout(() => {
        listDishes()
      }, 500)
    }
  })
}


/* 组件渲染后执行 */
listDishes()
getIngredientsList()
</script>

<template>
  <div class="app-container">
    <!-- 添加、修改表单 -->
    <el-dialog
        v-model="dishesFormVisible"
        :title="title"
        width="700">
      <!-- 表单 -->
      <el-form
          ref="dishesFormRef"
          :rules="dishesFormRules"
          :model="dishesForm"
          label-width="80">
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="dishesForm.name" placeholder="请输入菜品名称"/>
        </el-form-item>
        <el-form-item label="菜品图片" prop="url">
          <el-upload
              :headers="{'Authorization': tokenStore.accessToken}"
              :action="base_url + '/dishes-service/upload/image'"
              v-model:file-list="fileList"
              list-type="picture"
              :on-success="handleSuccess"
              :before-upload="handleBeforeUpload"
              :limit="fileLimit"
              :on-exceed="handleExceed"
              :on-remove="handleRemove">
            <el-button type="primary" plain icon="Plus">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">支持jpg/png，不能大于1MB</div>
            </template>
          </el-upload>
        </el-form-item>
        <!-- 主要食材 -->
        <div style="display: flex;">
          <el-form-item label="主要食材" prop="main">
            <el-select
                style="width: 200px; margin-right: 20px"
                v-model="dishesForm.main"
                clearable
                placeholder="请选择">
              <el-option
                  v-for="item in mainList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="份量" prop="mainNum">
            <el-input-number
                v-model="dishesForm.mainNum"
                :min="10"
                :max="1000"/>
          </el-form-item>
        </div>
        <!-- 辅助食材 -->
        <div style="display: flex;">
          <el-form-item label="辅助食材" prop="minor">
            <el-select
                style="width: 200px; margin-right: 20px"
                v-model="dishesForm.minor"
                clearable
                placeholder="请选择">
              <el-option
                  v-for="item in minorList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="份量" prop="minorNum">
            <el-input-number
                v-model="dishesForm.minorNum"
                :min="10"
                :max="1000"/>
          </el-form-item>
        </div>
        <!-- 配料 -->
        <div style="display: flex;">
          <el-form-item label="配料" prop="seasoning">
            <el-select
                style="width: 200px; margin-right: 20px"
                v-model="dishesForm.seasoning"
                clearable
                placeholder="请选择">
              <el-option
                  v-for="item in seasoningList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="份量" prop="seasoningNum">
            <el-input-number
                v-model="dishesForm.seasoningNum"
                :min="10"
                :max="1000"/>
          </el-form-item>
        </div>
        <el-form-item label="菜品描述" prop="description">
          <el-input
              type="textarea"
              v-model="dishesForm.description"
              placeholder="请输入菜品描述"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dishesFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm()">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查询表单 -->
    <el-form
        ref="queryFormRef"
        :model="queryForm"
        inline>
      <el-form-item label="菜品名称" prop="name">
        <el-input v-model="queryForm.name" clearable placeholder="请输入菜品名称"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain icon="Search" @click="search">搜索</el-button>
        <el-button type="info" plain icon="Refresh" @click="resetQueryForm">重置</el-button>
        <el-button type="success" plain icon="Plus" @click="handleAdd">添加</el-button>
      </el-form-item>
    </el-form>
    <!-- 列表数据 -->
    <el-table
        border
        stripe
        :data="dishesList"
        style="width: 100%;">
      <el-table-column type="index" label="编号" width="70" align="center"/>
      <el-table-column label="菜品名称" prop="name" align="center"/>
      <el-table-column label="主要食材" prop="mainName" align="center"/>
      <el-table-column label="辅助食材" prop="minorName" align="center"/>
      <el-table-column label="配料" prop="seasoningName" align="center"/>
      <el-table-column label="菜品封面" align="center">
        <template #default="scope">
          <el-image
              :src="base_url + scope.row.url"
              :preview-src-list="[base_url + scope.row.url]"
              preview-teleported
              style="width: 40px; height: 40px;"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="creatTime" width="280" align="center"/>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" plain circle icon="Edit" @click="handleEdit(scope.row)"/>
          <el-button type="danger" plain circle icon="Delete" @click="handleDelete(scope.row.id)"/>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <etoak-pager
        :page-sizes="[5, 10, 20]"
        :total="total"
        v-model:page-num="queryForm.pageNum"
        v-model:page-size="queryForm.pageSize"
        @get-data="listDishes"/>
  </div>
</template>

<style scoped>

</style>